import type { Directive, DirectiveBinding } from "vue";

interface ElType extends HTMLElement {
  handleClick: () => any;
  disabled: boolean
}

const throttle: Directive = {
  mounted(el: ElType, binding: DirectiveBinding) {
    if (typeof binding.value !== "function") {
      throw "callback must be a function";
    }
    el.handleClick = function () {
      let timer: NodeJS.Timeout | null = null;
      if (timer) {
        clearTimeout(timer);
      }
      if (!el.disabled) {
        el.disabled = true
        binding.value()
        timer = setTimeout(() => {
          el.disabled = false;
        }, 1000);
      }
    };

    el.addEventListener("click", el.handleClick);
  },
  beforeUnmount(el: ElType) {
    el.removeEventListener("click", el.handleClick);
  },
};

export default throttle;
